/* 
 * File:   ScriptHelpers.h
 * Author: artem
 *
 * Created on November 17, 2011, 1:40 PM
 */

#ifndef SCRIPTHELPERS_H
#define SCRIPTHELPERS_H

#include "lua/lua.hpp"
#include "Common.h"

template <typename T> T script_cast(lua_State *L, int idx)
{
	return static_cast<T>(lua_isuserdata(L, idx) ? lua_touserdata(L, idx) : 0);
}

#define script_new(L,T) new(L, #T) T

inline void* operator new(size_t size, lua_State *L, const char *mtname)
{
	void *ptr = lua_newuserdata(L, size);
	//ASSERT(ptr);
	luaL_getmetatable(L, mtname);
	//ASSERT(lua_istable(L, -1));
	lua_setmetatable(L, -2);
	return ptr;
}

template <typename T> int script_gc(lua_State *L)
{
	if (T *obj = script_cast<T*>(L, 1))
		obj->~T();
	return 0;
}

/*template <typename T> int script_create(lua_State *L)
{
	const T *obj = script_new(L, T);
	ASSERT(obj);
	return 1;
}*/

inline void script_bind_methods(lua_State *L, const char *name, const luaL_Reg *methods)
{
	luaL_register(L, name, methods);
	
	luaL_newmetatable(L, name);
	luaL_register(L, NULL, methods);
	
	lua_pushliteral(L, "__index");
	lua_pushvalue(L, -3);
	lua_rawset(L, -3);
	
	lua_pushliteral(L, "__metatable");
	lua_pushvalue(L, -3);
	lua_rawset(L, -3);
	
	lua_pop(L, 2);
}

#endif /* SCRIPTHELPERS_H */
